<?php

namespace App\Model;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Room extends BaseModel
{
    protected $table = 'room';
    protected $primaryKey = 'room_id';
    public $timestamps = false;
    CONST IMAGE = '/room/image_default.png';
    private $fields = ['room.room_id', 'room_uid', 'name', 'notice', 'image', 'room_type', 'create_timestamp', 'user_id', 'room_tag', 'certified', 'desc', 'room_rate', 'business_type', 'room_liang_type', 'heart', 'tally', 'melee', 'turntable', 'pk', 'spanpk','vote','fleet_king','fleet_peace','fleet_mult','room_score.reputation','background_pic','is_hide','room_mode'];
    private $roomTypeMap = [];


    protected $roomTopTable = 'room_top';
    protected $roomFinanceUserTable = 'room_finance_user';//房间绑定结算账户
    protected $roomWelcomeWordTable = 'room_welcome_word';//房间-欢迎语


    protected $table_room_open_time = 'room_open_time';

    protected $union_room_special_table = 'room_special_config';//房间特殊配置
    protected $union_room_table = 'union_room';//公会房间
    protected $union = 'union';//公会信息
    protected $userTable = 'user';

    //构建数据库中字段background_pic的链接
    public function getBackgroundPicAttribute($value)
    {
        if (!$value) return '';
        if (strpos($value[0], 'http:') !== false) {
            return $value;
        }
        return config('kkaudio.oss_url') . $value;
    }
    //构建数据库中字段img的链接
    public function getImageAttribute($value)
    {
        if (!$value) return '';
        if (strpos($value[0], 'http:') !== false) {
            return $value;
        }
        return config('kkaudio.oss_url') . $value;
    }

    public function user()
    {
        return $this->belongsTo(Number::class, 'user_id', 'user_id');
    }

    public function roomRecommend()
    {
        return $this->hasOne(RoomRecommend::class, 'room_id', 'room_id');
    }

    public function roomAdmin()
    {
        return $this->belongsTo(RoomAdmin::class, 'room_id', 'room_id');
    }
    public function getRoomList($input = [])
    {

        $limit = $input['limit'] ?: 10;
        $page = $input['page'] ?: 1;
        $business_type = $input['business_type'] ?? 1; //（0=小屋，1=CBD）
        $room_uid = $input['room_uid'] ?? 0;
        $room_id = $input['room_id'] ?? 0;
        $uuid = $input['uuid'] ?? 0;
        $name = $input['name'] ?? 0;
        $desc = $input['desc'] ?? 0;
        $notice = $input['notice'] ?? 0;
        $room_type = $input['room_type'] ?? 0;
        $certified = $input['certified'] ?? 1;
        $reputationType = $input['reputation_type'] ?? 0; //查询房间信誉分类型:1:≥60;2:50-60;3:≤50;

        $roomScoreModel = new RoomScore();

        $query = new self();
        if ($room_uid) $query = $query->where('room_uid', '=', $room_uid);
        if ($room_id) $query = $query->where('room.room_id', '=', $room_id);
        if ($name) $query = $query->where('name', 'like', "%$name%");
        if ($desc) $query = $query->where('desc', 'like', "%$desc%");
        if ($notice) $query = $query->where('notice', 'like', "%$notice%");
        if ($room_type) $query = $query->where('room_type', '=', $room_type);


        //房间信誉分
        if($reputationType == 1){ //≥60
            $query = $query->where('room_score.reputation','>=',60);
            $query = $query->orWhere('room_score.reputation', null);
            $query = $query->leftJoin('room_score', $this->table . '.room_id', '=', 'room_score.room_id');
        }elseif($reputationType == 2){ //50-60
            $query = $query->whereBetween('room_score.reputation', [50,60]);
            $query = $query->join('room_score', $this->table . '.room_id', '=', 'room_score.room_id');
        }elseif($reputationType == 3){ //≤50
            $query = $query->where('room_score.reputation','<=',50);
            $query = $query->rightJoin('room_score', $this->table . '.room_id', '=', 'room_score.room_id');
        }else{
            $query = $query->leftJoin('room_score', $this->table . '.room_id', '=', 'room_score.room_id');
        }

        $query = $query->where('certified', '=', $certified);

        $query = $query->with(['roomType:type_id,type_name'])->where('business_type', '=', $business_type)->orderBy('room_id', 'DESC')->whereHas('user', function ($query) use ($uuid) {
            $query->select('user_id');
            if ($uuid) $query->where(['uuid' => $uuid]);
        })->with(['user:user_id,uuid', 'roomRecommend:room_id,room_uid,coefficient','roomAdmin:room_id,admin_name']);
        $result = $query->paginate($limit, $this->fields, 'page', $page);
        $result = $this->objToArray($result);

        //整理房间信誉分
        if (!empty($result['data'])) {
            foreach ($result['data'] as &$r) {
                $r['reputation'] = ($r['reputation'] === null) ? $roomScoreModel::DEFAULT_REPUTATION : intval($r['reputation']);
                //获取房间所属公会信息
                $unionInfo = DB::connection($this->connection)->table($this->union_room_table)->where('room_id',$r['room_id'])->first();
                $unionInfo = $this->objToArray($unionInfo);
                if(empty($unionInfo))
                {
                    $r['union_name'] = '';
                }else{
                    $unionInfo = DB::connection($this->connection)->table($this->union)->where('id',$unionInfo['un_id'])->first();
                    $unionInfo = $this->objToArray($unionInfo);
                    $r['union_name'] = $unionInfo['name'];
                }

            }
        }

        return $result;
    }

    public function getRoomByRoomUid(Request $request)
    {
        return self::where('room_uid', 'like', "{$request->input('room_uid')}%")->get(['room_id', 'room_uid', 'name']);
    }

    public function getRoomInfo($room_uid = [])
    {
        $res = DB::connection($this->connection)->table($this->table)->whereIn('room_uid',$room_uid)->get(['room_id', 'room_uid', 'name', 'user_id']);
        return $this->objToArray($res);
    }

    public function roomType()
    {
        return $this->belongsTo(RoomType::class, 'room_type', 'type_id');
    }

    public function getRoomByRoomid($room_id)
    {
        return self::where('room_id', '=', "{$room_id}")->first(['room_uid', 'name','business_type']);
    }


    //更新
    public function updateData($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/update', $data, 'urlencoded', 'GET');
    }

    //新建cbd
    public function createCBDRoom($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/cbd/create', $data, 'urlencoded', 'GET');
    }

    //修改cbd
    public function updateCBDRoom($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/cbd/update', $data, 'urlencoded', 'POST');
    }

    public function searchRoomInfo($uuid = 0)
    {
        $sql = "SELECT uuid,room_id,nickname,room_uid,name,image FROM zb_user u LEFT JOIN zb_room r ON  u.user_id = r.user_id WHERE uuid LIKE '$uuid%'";
        return DB::connection('api')->select($sql);
    }

    /**
     * 是否团战
     * @param int $room_id 房间ID
     * @param int $state 1 开启; 0 关闭
     * @return mixed
     */
    public function setMeleeState(int $room_id, int $state)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/melee/setMelee', ['room_id' => $room_id, 'melee' => $state], 'json', 'POST');
    }

    /**
     * 是否计数
     * @param int $room_id
     * @param int $state 1 开启; 0 关闭
     * @return mixed
     */
    public function setTallyState(int $room_id, int $state)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/melee/setTally', ['room_id' => $room_id, 'tally' => $state], 'json', 'POST');
    }
//道具类型（1=礼物id，2=小屋礼物id，3=钻石value，4=珍珠value，5=小屋币value，6=金币value，7=魅力值value，
//8=财富值value，9=声望值value，10=名人值value，11=锤子value，12=商场商品id，14=靓号 15=隐身衣 16=足迹清除卡 17=甜蜜蛋糕 18=亲密度直升卡 19=防跟随
    /**
     * 是否转盘
     * @param int $room_id
     * @param int $state 1 开启; 0 关闭
     * @return mixed
     */
    public function setDialState(int $room_id, int $state)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/update', ['room_id' => $room_id, 'turntable' => $state], 'urlencoded', 'GET');
    }

    /**
     * pk
     * @param int $room_id
     * @param int $state 1 开启; 0 关闭
     * @return mixed
     */
    public function setPkState(int $room_id, int $state)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/update', ['room_id' => $room_id, 'pk' => $state], 'urlencoded', 'GET');
    }

    public function setSpanPkState(int $room_id, int $state)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/update', ['room_id' => $room_id, 'spanpk' => $state], 'urlencoded', 'GET');
    }

    public function getRoomByRoomids($room_id, $page = 1, $limit = 10)
    {
        return DB::connection($this->connection)->table($this->table)->whereIn('room_id', $room_id)
            ->leftJoin('user', 'user.user_id', '=', 'room.user_id')
            ->select('room_id', 'room_uid', 'name', 'uuid', 'nickname')
            ->get();
    }


    public function getShieldRoomList()
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/hot/black/get', [], 'urlencoded', 'GET');
    }

    public function addShieldRoom($room_id)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/hot/black/add', ['room_id' => $room_id], 'urlencoded', 'GET');
    }

    public function delShieldRoom($room_id)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/hot/black/del', ['room_id' => $room_id], 'urlencoded', 'GET');
    }


    public function getHighRoomList()
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/voice/check/high/get', [], 'urlencoded', 'GET');
    }

    public function addHighRoom($room_id)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/voice/check/high/add', ['room_id' => $room_id], 'urlencoded', 'GET');
    }

    public function delHighRoom($room_id)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/voice/check/high/del', ['room_id' => $room_id], 'urlencoded', 'GET');
    }

    public function getRoomCateType()
    {
        $res = DB::connection($this->connection)->table('room_type_cate')->get();
        return $this->objToArray($res);

    }

    public function getUserRoom($user_id)
    {
        $where['user_id'] = $user_id;
        $where['business_type'] = 1;
        $res = DB::connection($this->connection)->table($this->table)->where($where)->select('room_id','room_uid','name')->get();
        return $this->objToArray($res);
    }

    /**获取cdb房间的开厅时长
     * @param Request $request
     * @param $room_id
     * @return array
     */
    public function getOnlineTime(Request $request, $room_id)
    {
        $limit = $request->input('limit',10);
        $page = $request->input('page',1);
        $dateType = $request->input('date_type','month');
        $dateTimeArray = $request->input('value');

        $where = $begin = $end = $format = '';
        if($dateType === 'month'){
            if($dateTimeArray[0]){
                $begin = date('Y-m',strtotime($dateTimeArray[0]));
            }
            if($dateTimeArray[1]){
                $end = date('Y-m',strtotime($dateTimeArray[1]));
            }
            $format = '%Y-%m';
        } elseif ($dateType === 'year'){
            if($dateTimeArray[0]){
                $begin = date('Y',strtotime($dateTimeArray[0]));
            }
            if($dateTimeArray[1]){
                $end = date('Y',strtotime($dateTimeArray[1]));
            }
            $format = '%Y';
        }elseif ($dateType === 'week'){
            if($dateTimeArray){
                $begin = date('Y-m-d',strtotime("$dateTimeArray -1 day"));
            }
            if($dateTimeArray){
                $end = date('Y-m-d',strtotime("$dateTimeArray +5 day"));
            }

            $format = '%Y-%m-%d';
        }

        if($begin && !$end){
            $where .= " AND FROM_UNIXTIME(date, '{$format}')>='$begin'";
        }

        if(!$begin && $end){
            $where .= " AND FROM_UNIXTIME(date, '{$format}')<='$end'";
        }
        if($begin && $end){
            $where .= " AND FROM_UNIXTIME(date, '{$format}')>='$begin' AND FROM_UNIXTIME(date, '{$format}')<='{$end}'";
        }

        $sql = "SELECT * from zb_room_open_time  WHERE room_id={$room_id} $where order by date desc";
        $data = DB::connection($this->connection)->select($sql);
        $total = count($data);
        $data = collect($data)->forPage($page,$limit)->values()->toArray();
        foreach ($data as &$v){
            if(floor($v->more_five_mic_time/3600)<8){
                $v->font_color = '#ff0000';
            }else{
                $v->font_color = '#000000';
            }
            $v->date = date('Y-m-d' ,$v->date);
            $v->total_time = floor($v->total_time/3600).'小时'.(($v->total_time%3600)/60).'分';
            $v->more_five_mic_time = floor($v->more_five_mic_time/3600).'小时'.(($v->more_five_mic_time%3600)/60).'分';
            $v->less_five_mic_time = floor($v->less_five_mic_time/3600).'小时'.(($v->less_five_mic_time%3600)/60).'分';
        }
        return ['total' => $total, 'data' => $data,'sql'=>$sql];
    }

    public function getLess8RoomOpenTime(){
        $day = date('Y-m-d');
        $threeDayAgo = date('Y-m-d', strtotime('-3 days',time()));
        $sql =  "SELECT DISTINCT room_id FROM zb_room_open_time WHERE created_time BETWEEN '{$threeDayAgo}' and '{$day}'
and total_time < 3600 * 8 and room_id not in (SELECT DISTINCT room_id FROM zb_room_open_time WHERE created_time BETWEEN '{$threeDayAgo}' and '{$day}'
and total_time > 3600 * 8)";
        $roomIds = DB::connection('api')->select($sql);
        if (!$roomIds){
            return [];
        }
        $roomIds = array_column($roomIds,'room_id');
        $data = (new self())->whereIn('room_id',$roomIds)->where('certified',1)->with(['user:user_id,uuid,nickname'])->get();
        return $this->objToArray($data);
    }

    /**设置cbd房间车队权限
     * @param int $room_id
     * @param $fleet_king
     * @param $fleet_peace
     * @param $fleet_mult
     * @return mixed
     */
    public function setCarStatus(int $room_id,$fleet_king,$fleet_peace,$fleet_mult)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/set_car_status', ['room_id' => $room_id, 'fleet_king' => $fleet_king,'fleet_mult' => $fleet_mult,'fleet_peace' => $fleet_peace], 'json', 'POST');
    }

    //添加商品标签
    public function labelCreate($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/label/create', $data, 'json', 'POST');
    }

    //编辑某个商品标签
    public function labelEdit($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/label/edit', $data, 'json', 'POST');
    }

    public function getRoomListByIds($room_ids){
        return DB::connection($this->connection)->table($this->table)->whereIn('room_id',$room_ids)->get()->toArray();
    }
    /**
     * 获取特殊封面
     * @param int $roomid 房间id
     */
    public function getSpecialRoomInfo($roomid=0)
    {
        $where = function($q)use($roomid) {
            if (!empty($roomid)) {
                if (is_numeric($roomid))
                {
                    $q->where("roomid", $roomid);
                }
            }
        };
        $data = DB::connection($this->connection)->table($this->union_room_special_table)->where($where)->first();
        $data = $this->objToArray($data);
        return  $data;
    }

    /**
     * 新增或修改房间配置信息
     */
    public function insetOrUpdateData ($param)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/special/createorupdate', $param, 'json', 'POST');
    }
    /**
     * 删除房间设置
     */
    public function deleteeData($param)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/room/special/delete', $param, 'json', 'POST');
    }

    //新增置顶房间
    public function topRoomCreate($data){
        $code = 50000;
        $msg = '失败';
        do {
            if(empty($data['room_id'])) {
                $msg = '参数错误';
                break;
            }
            $res = curl_request(getKkaudioApiUrl() . '/inner/room/topRoomCreate', $data, 'json', 'POST');
            if(isset($res['code']) && $res['code']==0) {
                $code = 20000;
                $msg = '成功';
                break;
            }else{
                $msg = empty($res['msg']) ? '失败' : $res['msg'];
                break;
            }
            
        } while (false);

        return ['code'=>$code, 'msg'=>$msg];
    }

    //修改置顶房间
    public function topRoomUpdate($data){
        $code = 50000;
        $msg = '失败';
        do {
            if(empty($data['room_id'])) {
                $msg = '参数错误';
                break;
            }
            $res = curl_request(getKkaudioApiUrl() . '/inner/room/topRoomUpdate', $data, 'json', 'POST');
            if(isset($res['code']) && $res['code']==0) {
                $code = 20000;
                $msg = '成功';
                break;
            }else{
                $msg = empty($res['msg']) ? '失败' : $res['msg'];
                break;
            }
            
        } while (false);

        return ['code'=>$code, 'msg'=>$msg];
    }

    //删除置顶房间
    public function topRoomDel($data){
        $code = 50000;
        $msg = '失败';
        do {
            if(empty($data['room_id'])) {
                $msg = '参数错误';
                break;
            }
            $res = curl_request(getKkaudioApiUrl() . '/inner/room/topRoomDel', $data, 'json', 'POST');
            if(isset($res['code']) && $res['code']==0) {
                $code = 20000;
                $msg = '成功';
                break;
            }else{
                $msg = empty($res['msg']) ? '失败' : $res['msg'];
                break;
            }
        } while (false);

        return ['code'=>$code, 'msg'=>$msg];
    }

    //置顶房间列表
    public function topRoomList(Request $request)
    {
        $room_id = $request->input('room_id');
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);

        $query = DB::connection($this->connection)->table($this->roomTopTable)->where('is_delete', 0);
        if(!empty($room_id)) {
            $query = $query->where('room_id', $room_id);
        }
        $result = $query->orderBy('id', 'desc')->paginate($limit, ['*'], 'page', $page);
        $result = objToArray($result);

        if(!empty($result['data'])) {
            $roomIds = array_column($result['data'], 'room_id');
            $roomList = DB::connection($this->connection)->table($this->table)->whereIn('room_id', $roomIds)->get();
            $roomList = array_column(objToArray($roomList), null, 'room_id');

            $roomIdStr = implode(',', $roomIds);
            $openList = curl_request(getKkaudioApiUrl() . '/inner/room/getOpenRoomIds', ['roomIds'=>$roomIdStr], 'urlencoded', 'GET');
            $openList = empty($openList['data']['list']) ? [] : $openList['data']['list'];

            foreach($result['data'] as $key=>$val) {
                $roomInfo = empty($roomList[$val['room_id']]) ? [] : $roomList[$val['room_id']];

                $val['room_name'] = empty($roomInfo['name']) ? '' : $roomInfo['name'];
                $val['room_uid'] = empty($roomInfo['room_uid']) ? '' : $roomInfo['room_uid'];
                $val['open_status'] = empty($openList[$val['room_id']]) ? 0 : 1;

                $result['data'][$key] = $val;
            }
        }

        return $result;
    }

    //设置房间分成用户
    public function setRoomFinanceUser($params, $user)
    {
        $params['admin_id'] = $user['id'];
        $res = curl_request(getKkaudioApiUrl() . '/inner/room/setRoomFinanceUser', $params, 'urlencoded', 'POST');
        return curlResultHandle($res);
    }

    //获取房间分成用户
    public function getRoomFinanceUser(Request $request)
    {
        $room_id = (int) $request->input('room_id');
        if(empty($room_id)) {
            return ['code'=>50001, 'data'=>[], 'msg'=>'参数错误'];
        }
        $res = DB::connection($this->connection)->table($this->roomFinanceUserTable)->where('is_delete', 0)
            ->where('room_id', $room_id)
            ->first();
        $res = objToArray($res);

        $result = [];
        if(!empty($res)) {
            $userId = $res['user_id'];
            $userInfo = DB::connection($this->connection)->table($this->userTable)->where('user_id', $userId)->select('user_id','nickname','uuid')->first();
            $userInfo = objToArray($userInfo);
            $result['user_id'] = $userId;
            $result['uuid'] = empty($userInfo['uuid']) ? '' : $userInfo['uuid'];
            $result['nickname'] = empty($userInfo['nickname']) ? '' : $userInfo['nickname'];
        }

        return ['code'=>20000, 'data'=>$result, 'msg'=>'ok'];
    }
    //房间欢迎语列表
    public function listRoomWelcomeWord(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $union_id = $request->input('union_id', 0);
        $room_id = $request->input('room_id', 0);
        $union_name = $request->input('union_name', '');
        $content = $request->input('content', '');
        $audit_status = $request->input('audit_status', 0);

        $query = DB::connection($this->connection)->table($this->roomWelcomeWordTable.' as a')
            ->leftJoin($this->union.' as b', "a.union_id", "=", "b.id")
            ->leftJoin($this->table.' as c', "a.room_id", "=", "c.room_id")
            ->orderBy('a.id', 'desc')
            ->select(['a.id','a.union_id','a.room_id','a.room_id','a.content','a.audit_status','a.created_at','a.updated_at'
                ,'b.name as union_name'
                ,'c.name as room_name'
                ])
            ->where('a.is_delete', 0);
        if(!empty($union_id)) {
            $query = $query->where('a.union_id', $union_id);
        }
        if(!empty($room_id)) {
            $query = $query->where('a.room_id', $room_id);
        }
        if(!empty($union_name)) {
            $query = $query->where('b.name', 'like', '%'.$union_name.'%');
        }
        if(!empty($content)) {
            $query = $query->where('a.content', 'like', '%'.$content.'%');
        }
        if(!empty($audit_status)) {
            $query = $query->where('a.audit_status', $audit_status);
        }

        $result = $query->paginate($limit, ['*'], 'page', $page);
        $result = objToArray($result);
        foreach($result['data'] as $key=>$val) {

            $result['data'][$key] = $val;
        }
        $result = ['data'=>$result['data'], 'total'=>$result['total']];

        return $result;
    }

    //审核房间欢迎语
    public function auditRoomWelcomeWord($data, $user){
        $data['admin_id'] = $user['id'];
        $res = curl_request(getKkaudioApiUrl() . '/inner/room/auditRoomWelcomeWord', $data, 'urlencoded', 'POST');
        return curlResultHandle($res);
    }

    //一键通过房间欢迎语
    public function auditBatchRoomWelcomeWord($data, $user){
        $data['admin_id'] = $user['id'];
        $res = curl_request(getKkaudioApiUrl() . '/inner/room/auditBatchRoomWelcomeWord', $data, 'urlencoded', 'POST');
        return curlResultHandle($res);
    }

    //是否隐藏房间
    public function hideRoom($roomId, $status){
        $data = [
            'room_id' => $roomId,
            'status' => $status,
        ];
        $res = curl_request(getKkaudioApiUrl() . '/inner/room/hideRoom', $data, 'urlencoded', 'POST');
        return curlResultHandle($res);
    }
}

